import {defineStore} from 'pinia'
import {ref,computed} from 'vue'
import http from '../utils/http'
import router from '../router'
let token=localStorage.getItem("Authorization")
let userinfo=JSON.parse(localStorage.getItem("UserInfo"))
let mypermissions=JSON.parse(localStorage.getItem("permissions"))
export default  defineStore("useUserStore",()=>{
    let Authorization=ref(token);
    let UserInfo=ref(userinfo);
    let Permissions=ref(mypermissions);
    let login=async (payload)=>{
        let re=await http.get("/user/login",{params:payload});
            if(re&&re.Authorization){
                Authorization.value=re.Authorization;
                UserInfo.value=re;
                localStorage.setItem("Authorization",Authorization.value)
                localStorage.setItem("UserInfo",JSON.stringify(UserInfo.value))
                ElMessage({
                    type:"success",
                    message:"登录成功"
                });
                router.push("/manage");
            }else{
                ElMessage({
                    type:"error",
                    message:"账号密码错误登录失败!"
                })
            }
    }
    let logOut=()=>{
       localStorage.clear();
       Authorization.value="";
       UserInfo.value={};
       Permissions.value={};
       router.push("/login");
    }
    let getPermission=async ()=>{
        if(UserInfo.value && !UserInfo.value._id) return;
        let permissions=await http.get("/admin/role",{params:{userid:UserInfo.value._id}});
        Permissions.value=permissions;
        localStorage.setItem("permissions",JSON.stringify(permissions));
    }
    let isLogin=computed(()=>{
        return !!Authorization.value
    })
    return {
        Authorization,UserInfo,Permissions,login,logOut,getPermission,isLogin
    }
});